<template>
  <el-dialog draggable v-model="dialogVisible" :title="dialogProps.title" width="80%">
    <div style="margin-top: -10px; margin-bottom: 10px">
      <el-input v-model="searchKw" placeholder="请输入" :prefix-icon="Search" @input="searchInp" />
    </div>
    <div class="selector-container">
      <TreeFilter
        label="name"
        :show-search="false"
        :data="treeFilterData"
        @change="changeTreeFilter"
        :default-value="initParam"
      />
      <div class="table-box">
        <ProTable
          ref="proTable"
          row-key="id"
          :max-height="340"
          :tool-button="false"
          :margin-border="false"
          :indent="20"
          :data="tableData"
          :columns="dialogProps.columns"
          :pagination="false"
          @selection-change="changeSelection"
        >
        </ProTable>
      </div>
    </div>
    <div class="selector-footer" v-if="dialogProps.selType === 'selection'">
      <div class="flx-justify-between pt10 pb10">
        <span>已选择({{ tags.length }})</span>
        <el-button type="danger" @click="clearSelection">清空</el-button>
      </div>
      <div class="inner">
        <el-tag v-for="tag in tags" :key="tag.id" class="mr6 mb6" closable @close="handleDelTag(tag.id)">
          {{ tag.name }}
        </el-tag>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button type="primary" @click="onEmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="selectGoods">
import { ref, nextTick, watch } from "vue";
import { Goods } from "@/api/interface";
import { Search } from "@element-plus/icons-vue";
import { ProTableInstance } from "@/components/ProTable/interface";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { useDebounceFn } from "@vueuse/core";
interface DialogProps {
  title: string;
  isView: boolean;
  selType?: string;
  selTags?: any[];
  columns?: any[];
  idName?: string;
  index?: number | string;
  searchVal?: string | number;
  mate?: string;
  apiParams?: {};
  api?: (params: any) => Promise<any>;
  treeApi?: (params: any) => Promise<any>;
  type?: string;
}
const dialogProps = ref<DialogProps>({
  isView: false,
  selType: "selection",
  title: "",
  index: -1,
  searchVal: "",
  mate: "id"
});
const proTable = ref<ProTableInstance>();

const initParam = ref(0);
const dialogVisible = ref(false);
const treeFilterData = ref<any>([]);
const tableData = ref<Goods.ResGoodsList[]>([]);
const tags = ref<Goods.ResGoodsList[]>([]);
const searchKw = ref("");
const emit = defineEmits(["selectedList", "radio"]); // 指定组件可以触发的事件

// 树形筛选切换
const changeTreeFilter = (id: number) => {
  initParam.value = id;
  tableData.value = [];
  getTableData();
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogProps.value.selType = params.selType || "selection";
  tags.value = dialogProps.value.selTags;
  searchKw.value = dialogProps.value.searchVal;
  dialogVisible.value = true;
  getTreeFilter();
};

const getTreeFilter = async () => {
  const { data } = await dialogProps.value.treeApi();
  treeFilterData.value = data.list || data;
  initParam.value = 0;
  await getTableData();
};

// 搜索数据
const searchInp = useDebounceFn(() => {
  getTableData();
}, 800);

const getTableData = () => {
  tableData.value = [];
  dialogProps.value
    .api({
      name: searchKw.value,
      pageNum: 1,
      pageSize: 9999,
      isDefault: 0,
      ...dialogProps.value.apiParams,
      [dialogProps.value.idName]: initParam.value
    })
    .then(res => {
      // 处理数据
      tableData.value = JSON.parse(JSON.stringify(res.data.list)) ?? [];
      if (dialogProps.value.selType === "selection") {
        nextTick(() => {
          // const tags_Ids = tags.value.map(i => i.id);
          const tags_Ids = tags.value.map(i => i[dialogProps.value.mate]);
          tableData.value.forEach(item => {
            if (tags_Ids.includes(item[dialogProps.value.mate])) {
              proTable.value!.element.toggleRowSelection(item, true);
            }
          });
        });
      }
    })
    .catch(() => {
      tableData.value = [];
    });
};

const handleDelTag = (tag?: string | number) => {
  let index1 = tags.value.findIndex(item => item.id === tag);
  let index2 = tableData.value.findIndex(item => item.id === tag);
  if (index1 > -1) {
    tags.value.splice(index1, 1);
  }
  if (index2 > -1) {
    proTable.value!.element.toggleRowSelection(tableData.value[index2], false);
  }
};

// 清空选择
const clearSelection = () => {
  if (tags.value.length !== 0) {
    tags.value.splice(0, tags.value.length);
    proTable.value!.element.clearSelection();
  }
};

// 提交数据（选择菜品）
const onEmit = () => {
  if (dialogProps.value.selType === "radio") {
    emit("radio", { data: proTable.value!.radio, index: dialogProps.value.index });
  } else if (dialogProps.value.selType === "selection") {
    emit("selectedList", {
      list: tags.value,
      title: dialogProps.value.title,
      index: dialogProps.value.index,
      type: dialogProps.value.type
    });
  }
  // 搜索的 内容
  searchKw.value = "";
  dialogVisible.value = false;
};

watch(dialogVisible, newValue => {
  if (!newValue) {
    tags.value = [];
    proTable.value!.element.clearSelection();
  }
});

const changeSelection = (selection: any[]) => {
  tags.value = selection;
};

defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
